package cn.collin.commons.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 301��ת
 * @author collin.code@gmail.com
 *
 */
public class RedirectFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		String hostName = "http://" + req.getServerName();
		if (hostName.startsWith("http://cpyjy.com")) {
			HttpServletResponse response = (HttpServletResponse) resp;
			HttpServletRequest httpRequest = (HttpServletRequest) req;
			String queryString = (httpRequest.getQueryString() == null ? ""
					: "?" + httpRequest.getQueryString());
			response.setStatus(301);
			String requestUrl = httpRequest.getRequestURL().toString();
			requestUrl = requestUrl.replace("http://cpyjy.com",
					"http://www.cpyjy.com");

			response.setHeader("Location", requestUrl + queryString);
			response.setHeader("Connection", "close");
		} else {
			chain.doFilter(req, resp);
		}
	}

	public void init(FilterConfig config) throws ServletException {

	}

}
